package com.hanoi.wiki.controller.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hanoi.wiki.controller.RoleController;
import com.hanoi.wiki.exception.FunctionalException;
import com.hanoi.wiki.manager.RoleManager;
import com.hanoi.wiki.model.json.BaseJsonObject;
import com.hanoi.wiki.model.json.ResponseJsonObject;
import com.hanoi.wiki.model.json.RoleJson;

@Controller
@RequestMapping("/rol")
public class RoleControllerImpl extends BaseControllerImpl implements RoleController {

	@Autowired
	private RoleManager roleManager;
	
	public @ResponseBody ResponseJsonObject getRole(@PathVariable int id) {
		ResponseJsonObject jsonObject = new ResponseJsonObject();
		List<BaseJsonObject> objects = new ArrayList<BaseJsonObject>();
		
		RoleJson json = null;
		try {
			json = roleManager.get(id);
		} catch (FunctionalException e) {
			e.printStackTrace();
		}	
		
		objects.add(json);
		jsonObject.setResults(objects);
		
		return jsonObject;
	}

	public @ResponseBody ResponseJsonObject saveRole(@RequestBody RoleJson role) {
		ResponseJsonObject jsonObject = new ResponseJsonObject();
		List<BaseJsonObject> objects = new ArrayList<BaseJsonObject>();
		int id = 0;
		try {
			id = roleManager.save(role);
		} catch (FunctionalException e) {
			e.printStackTrace();
		}
		role.setId(id);
		objects.add(role);
		jsonObject.setResults(objects);
		
		return jsonObject;
	}

	public @ResponseBody ResponseJsonObject removeRole(@PathVariable int id) {
		ResponseJsonObject jsonObject = new ResponseJsonObject();
		List<BaseJsonObject> objects = new ArrayList<BaseJsonObject>();
		RoleJson json = null;
		
		try {
			json = roleManager.get(id);
			roleManager.remove(id);
		} catch (FunctionalException e) {
			e.printStackTrace();
		}
		
		objects.add(json);
		jsonObject.setResults(objects);
		
		return jsonObject;
	}

	public @ResponseBody ResponseJsonObject getRoleList() {
		ResponseJsonObject jsonObject = new ResponseJsonObject();
		List<BaseJsonObject> objects = new ArrayList<BaseJsonObject>();
		
		try {
			objects.addAll(roleManager.getList());
		} catch (FunctionalException e) {
			e.printStackTrace();
		}
		
		jsonObject.setResults(objects);
		
		return jsonObject;
	}

	public @ResponseBody ResponseJsonObject updateRole(@RequestBody RoleJson role) {
		ResponseJsonObject jsonObject = new ResponseJsonObject();
		List<BaseJsonObject> objects = new ArrayList<BaseJsonObject>();
		
		try {
			roleManager.update(role);
		} catch (FunctionalException e) {
			e.printStackTrace();
		}
		
		objects.add(role);
		jsonObject.setResults(objects);
		
		return jsonObject;
	}

}
